package com.jloading.ui;
import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;
import com.pope945.mypanel.ComBrowserUrlPanel;
import com.util.ReadConfig;
import com.util.cmd.MyCMD;

import exchange4Server.Messager4Server;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

import org.jdesktop.application.Application;

import pope.jloading.TaskTableModel;

import pope.jloading.TaskModel;
import pope.jloading.mycell.ColumnCellRenderer;
import pope.jloading.mycell.ProgressBarRenderer;

import pope.jloading.Elog;
import pope.jloading.JLoadingException;
import pope.jloading.TaskManager;
import pope.table.MusicModel;
import pope.table.MusicTableModel;
import softutil.UnInstall;

import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Choose2DownloadPanel extends javax.swing.JPanel {
	private JPanel jPanel1;
	private JPanel jPanel2;
	private JRadioButton jRadioButton2;
	private JRadioButton jRadioButton1;
	
	private javax.swing.JTable jTable1;
	private JScrollPane jScrollPane1;
	private JButton jButton6;
	private JTextField jTextField1;
	private JButton jButton1;
	private JButton jButton5;
	private JRadioButton jRadioButton4;
	private JRadioButton jRadioButton3;
	private JButton jButton2;
	private JButton jButton3;
	private JButton jButton4;
	
	private String downloadingUrl;
	private String sid;
	

	private String path;
	
	private String action;
	
	private String lastAction;

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}	
	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame frame = new JFrame();
				frame.getContentPane().add(new Choose2DownloadPanel());
				frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
				frame.pack();
				frame.setVisible(true);
			}
		});
	}
	/**
	 * 该构造函数为 不进行切换操作
	 *
	 */
	public Choose2DownloadPanel() {
		super();
		
		initGUI();
	}
	
	
	
	/**
	 * 
	 * @param isChangeSerNum
	 */
	private void initGUI( ) {
		
		try {			
			{
				AnchorLayout thisLayout = new AnchorLayout();
					this.setLayout(thisLayout);
					this.setSize(492, 398);
				
				{
					jPanel1 = new JPanel();
					AnchorLayout jPanel1Layout = new AnchorLayout();
					jPanel1.setLayout(jPanel1Layout);
					this.add(jPanel1, new AnchorConstraint(1, 257, 1001, 1, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
					jPanel1.setPreferredSize(new java.awt.Dimension(126, 398));
					jPanel1.setName("jPanel1");
					{
						jButton6 = new JButton();
						jPanel1.add(jButton6, new AnchorConstraint(837, 876, 918, 154, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
						jButton6.setPreferredSize(new java.awt.Dimension(91, 32));
						jButton6.setName("jButton6");
						
						jButton6.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {                            	                            	   
                                  try {
									seeSerNum();
								} catch (IOException e1) {									
									e1.printStackTrace();
								}
                            }
                    });
					}

					String av1=ReadConfig.readValue("config.ini","name.antiv_0001");
					String av2=ReadConfig.readValue("config.ini","name.antiv_0002");
					String av3=ReadConfig.readValue("config.ini","name.antiv_0003");
					String av4=ReadConfig.readValue("config.ini","name.antiv_0004");
					
					
						jRadioButton1 = new JRadioButton(av1);
						jPanel1.add(jRadioButton1, new AnchorConstraint(56, 916, 126, 99, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
						jRadioButton1.setName("jRadioButton1");
					
						jRadioButton2 = new JRadioButton(av2);
						jPanel1.add(jRadioButton2, new AnchorConstraint(197, 916, 267, 99, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
						jRadioButton2.setName("jRadioButton2");
						
						{
		    				jRadioButton3 = new JRadioButton(av3);
		    				jPanel1.add(jRadioButton3, new AnchorConstraint(322, 908, 400, 99, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
		    				jRadioButton3.setName("jRadioButton3");
		    				jRadioButton3.setPreferredSize(new java.awt.Dimension(102, 31));
		    			}
		    			{
		    				jRadioButton4 = new JRadioButton(av4);
		    				jPanel1.add(jRadioButton4, new AnchorConstraint(463, 916, 533, 99, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
		    				jRadioButton4.setName("jRadioButton4");
		    				jRadioButton4.setPreferredSize(new java.awt.Dimension(103, 28));
		    			}
					
					
					
						jPanel2 = new JPanel();
						AnchorLayout jPanel2Layout = new AnchorLayout();
						jPanel2.setLayout(jPanel2Layout);
						this.add(jPanel2, new AnchorConstraint(1, 1001, 951, 269, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
						jPanel2.setPreferredSize(new java.awt.Dimension(360, 378));
						jPanel2.setName("jPanel2");

						jScrollPane1 = new javax.swing.JScrollPane();
						jPanel2.add(jScrollPane1, new AnchorConstraint(1, 995, 821, 1, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
						jScrollPane1.setPreferredSize(new java.awt.Dimension(358, 310));
						
							jButton1 = new JButton("开始");
							jButton2 = new JButton("暂停");
							jButton3 = new JButton("停止");
							jButton4 = new JButton("删除");
							jPanel2.add(jButton1, new AnchorConstraint(916, 270, 988, 65, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
							jButton1.setPreferredSize(new java.awt.Dimension(74, 27));
							jPanel2.add(jButton2, new AnchorConstraint(916, 468, 988, 301, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
							jButton2.setPreferredSize(new java.awt.Dimension(60, 27));
							jPanel2.add(jButton3, new AnchorConstraint(921, 670, 988, 498, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
							jButton3.setPreferredSize(new java.awt.Dimension(62, 25));
							jPanel2.add(jButton4, new AnchorConstraint(919, 948, 993, 726, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
							jButton4.setPreferredSize(new java.awt.Dimension(80, 28));

							jTable1 = new javax.swing.JTable();
							jScrollPane1.setViewportView(jTable1);
							this.jTable1.setRowHeight(22);
							jTable1.setModel( new TaskTableModel());//显示表头
							jTable1.setPreferredSize(new java.awt.Dimension(355, 267));
							
						
					}

					ActionListener a = new ActionListener() {
	    				public void actionPerformed(ActionEvent ae) {
	    					if (ae.getSource() ==jRadioButton1 ) {
	    						String urlstring=ReadConfig.readValue("config.ini","url.antiv_0001");	    						
								downloadingUrl=urlstring;
								sid="antiv_0001";
								if(action.equals("xiazai"))
									lastAction="xiazai";
								else lastAction="qiehuan";
	    					} else if(ae.getSource() ==jRadioButton2 ) {
	    						String urlstring=ReadConfig.readValue("config.ini","url.antiv_0002");	    						
								downloadingUrl=urlstring;
								sid="antiv_0002";
								if(action.equals("xiazai"))
									lastAction="xiazai";
								else lastAction="qiehuan";
	    					}else if(ae.getSource() ==jRadioButton3 ) {
	    						String urlstring=ReadConfig.readValue("config.ini","url.antiv_0003");	    						
								downloadingUrl=urlstring;
								sid="antiv_0003";
								if(action.equals("xiazai"))
									lastAction="xiazai";
								else lastAction="qiehuan";
	    					}else if(ae.getSource() ==jRadioButton4) {
	    						String urlstring=ReadConfig.readValue("config.ini","url.antiv_0004");	    						
								downloadingUrl=urlstring;
								sid="antiv_0004";
								if(action.equals("xiazai"))
									lastAction="xiazai";
								else lastAction="qiehuan";
	    					}else if(ae.getSource() ==jButton5) {	    						
	    								
	    							if(downloadingUrl!=null&&!(downloadingUrl.trim()).equals("")){//
	    								System.out.println("sssss downloadingUrl:"+downloadingUrl+" lastAction:"+lastAction+" sid:"+sid);
	    							if(	!checkNames(downloadingUrl))//不存在重名文件
	    								{	    								
	    									confirm2Download(downloadingUrl,sid,lastAction);
	    									} else {//存在相同文件
	    										System.out.println(" :"+lastAction);	   
	    										
	    										Messager4Server m4s=new Messager4Server();
	    										m4s.saveFile("info", "exitFileSid", sid);
	    										System.out.println("存在相同文件 写入exitFileSid是 ："+sid);
	    										 
	    										showAlertNames(lastAction);
	    										
	    										}
	    									
	    								
	    								}else{
	    									//将文件写入 
	    									
	    									showAlert();
	    								}
	    					
	    					}
	    				}
	    			};
	    			
	    			
	    			ButtonGroup buttonGroup1 = new ButtonGroup();

	    			buttonGroup1.add(jRadioButton1);
	    			jRadioButton1.setPreferredSize(new java.awt.Dimension(103, 28));

	    			buttonGroup1.add(jRadioButton2);
	    			jRadioButton2.setPreferredSize(new java.awt.Dimension(103, 28));
	    			buttonGroup1.add(jRadioButton3);
	    			buttonGroup1.add(jRadioButton4);
	    			{
	    				jButton5 = new JButton();
	    				jPanel1.add(jButton5, new AnchorConstraint(616, 797, 697, 194, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
	    				jButton5.setName("jButton5");
	    				jButton5.setPreferredSize(new java.awt.Dimension(76, 32));
	    				
	    			
	    			}
	    			{
	    				jTextField1 = new JTextField();
	    				jPanel1.add(jTextField1, new AnchorConstraint(742, 908, 822, 99, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
	    				jTextField1.setName("jTextField1");
	    				jTextField1.setPreferredSize(new java.awt.Dimension(102, 32));
	    			}

	    			jRadioButton1.addActionListener(a);
	    			jRadioButton2.addActionListener(a);	  
	    			jRadioButton3.addActionListener(a);	    				    			
	    			jRadioButton4.addActionListener(a);	 
	    			
	    			jButton5.addActionListener(a);
					
					
				}

				 TableColumnModel tcm = jTable1.getColumnModel();
			        int columns = tcm.getColumnCount();
			        for (int i = 0; i < columns; i++) {
			            tcm.getColumn(i).setCellRenderer(new ColumnCellRenderer());
			        }
			        
			        TableColumn tc = tcm.getColumn(TaskModel.COLUMN_PROCESS);
			        tc.setCellRenderer(new ProgressBarRenderer());
			        
			        // 设置任务管理
			        TaskManager tManager = TaskManager.getInstance();
			        tManager.setTable(jTable1);
			        tManager.loadTasks();
			        
			        
			        jButton1.addActionListener(new java.awt.event.ActionListener() {
	    	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	    	                jButton1ActionPerformed(evt);
	    	            }
	    	        });
					jButton2.addActionListener(new java.awt.event.ActionListener() {
	    	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	    	                jButton2ActionPerformed(evt);
	    	            }
	    	        });
					jButton3.addActionListener(new java.awt.event.ActionListener() {
	    	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	    	                jButton3ActionPerformed(evt);
	    	            }
	    	        });
					jButton4.addActionListener(new java.awt.event.ActionListener() {
	    	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	    	                jButton4ActionPerformed(evt);
	    	            }
	    	        });

			Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	protected void showAlert() {
		JLabel jlb=new JLabel("<html> <a href=''>你没有选择产品</a> <br>  </html>");	      
		JOptionPane.showMessageDialog(this, 
				jlb, "About  ",JOptionPane.INFORMATION_MESSAGE);
		
	}
	
	/**
	 * showAlert about has double name
	 */
	protected void showAlertNames(String action) {
		/*int option = JOptionPane.showConfirmDialog(null, "已经存在该下载文件，是否进行下一步操作", "提示",JOptionPane.YES_NO_OPTION);
		if (option == JOptionPane.YES_OPTION){
			System.out.println("这里执行下一步操作");											
		} else {
			System.out.println("不动作");
			
		}*/
		
		JLabel jlb=new JLabel("<html> <a href=''>已经存在下载文件，进行下一步操作</a> <br>  </html>");	      
		JOptionPane.showMessageDialog(this, jlb, "提示 ",JOptionPane.INFORMATION_MESSAGE);
		 
		String path1 = downloadingUrl.substring(downloadingUrl.lastIndexOf("/")).trim();
    	String name=path1.substring(1);    
    	
    	Messager4Server m4s=new Messager4Server();
    		try {
				String sid=m4s.readFile("info", "exitFileSid");
				System.out.println("存在文件 切换的 sid:"+sid);
			UnInstall.confirm2Uninstall(name,action,sid);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
							
	}

	
	
	/**
	 * 确定按钮事件
	 * @param downloadingUrl
	 */
	protected void confirm2Download(String downloadingUrl,String sid,String action) {
		try {			
			URL url;
			try {
				url = new URL(downloadingUrl);
				String name=getFileName(url);
				
				addTasks(name,downloadingUrl,sid,action);	//TODO
				Messager4Server m4s=new Messager4Server();
				m4s.saveFile("info", "2changeSid",sid);
				
			} catch (MalformedURLException e) {										
				e.printStackTrace();
			}    							
			
		} catch (JLoadingException e) {							
			e.printStackTrace();
		}
		
	}

	/**
	 * 查看序列号
	 * @throws IOException 
	 *
	 */
		protected void seeSerNum() throws IOException {
			Messager4Server m4s=new Messager4Server();
			 String serNum=m4s.readFile("info", "serNum");			
			if(serNum!=null){
			jTextField1.setText(serNum);	
			}else{
				jTextField1.setText("没有成功获取序列号");
			}
			
		}
		
		
		/**
		 * 
		 * @param url
		 * @return
		 */

	protected String getFileName(URL url) {
		
		String fileName = url.getFile();
		//在此对象表示的字符序列中最后一次出现该字符的索引，如果未出现该字符，则返回 -1
		return fileName.substring(fileName.lastIndexOf('/') + 1);	
	}
	
	protected void jButton4ActionPerformed(ActionEvent evt) {
		deleteTasks();		
	}

	protected void jButton3ActionPerformed(ActionEvent evt) {
		stopTasks();		
	}

	protected void jButton2ActionPerformed(ActionEvent evt) {
		pauseTasks();		
	}

	protected void jButton1ActionPerformed(ActionEvent evt) {
		startTasks();		
	}
	
	private void startTasks() {
        TaskManager tManager = TaskManager.getInstance();
//        tManager.setTable(jTable1);// THIS IS ADD BY POPE
        int[] keys = jTable1.getSelectedRows();//TODO 为什么JTable why no action
        TaskTableModel ttm = (TaskTableModel) jTable1.getModel();
        for (int key : keys) {
            tManager.startTask(ttm.getTask(key));
        }
    }
    
    private void pauseTasks() {
        TaskManager tManager = TaskManager.getInstance();
        int[] keys = jTable1.getSelectedRows();
        TaskTableModel ttm = (TaskTableModel) jTable1.getModel();
        for (int key : keys) {
            tManager.pauseTask(ttm.getTask(key));
        }
    }
    
    private void stopTasks() {
        TaskManager tManager = TaskManager.getInstance();
        int[] keys = jTable1.getSelectedRows();
        TaskTableModel ttm = (TaskTableModel) jTable1.getModel();
        for (int key : keys) {
            tManager.stopTask(ttm.getTask(key));
        }
    }
    
    private void deleteTasks() {
        ArrayList<TaskModel> taskToDel = new ArrayList<TaskModel>();
        int[] keys = jTable1.getSelectedRows();
        TaskTableModel ttm = (TaskTableModel) jTable1.getModel();
        for (int i = 0; i < keys.length; i++) {
            int k = keys[i];
            taskToDel.add(ttm.getTask(k));
        }
        TaskManager tManager = TaskManager.getInstance();
        tManager.deleteTasks(taskToDel);
    }

	/**
     * 添加任务
     */
    private void addTasks() throws JLoadingException {
        TaskManager tManager = TaskManager.getInstance();
        TableModel tableModel = jTable1.getModel();
        int[] keys = jTable1.getSelectedRows();
        if (tableModel instanceof MusicTableModel) {//上面表的内容
            MusicTableModel mtm = (MusicTableModel) tableModel;
            List<MusicModel> musics = mtm.getValues();
            
            for (int key : keys) {
                MusicModel mm = musics.get(key);
                tManager.addTask(mm.getName(), mm.getUrl());
            }
        }
    }
    
    private void addTasks(String name,String url,String sid,String action) throws JLoadingException {
        TaskManager tManager = TaskManager.getInstance();
        TableModel tableModel = jTable1.getModel();
        int[] keys = jTable1.getSelectedRows();
//        if (tableModel instanceof MusicTableModel) {
//            MusicTableModel mtm = (MusicTableModel) tableModel;
//            List<MusicModel> musics = mtm.getValues();
            
            for (int i=0;i<1;i++) {
                tManager.addTaskSid(name, url,sid,action);
                startTasks();
            }
           
            
//        }
    }
    
    
    private  boolean checkNames(String url) {            	
        	String path1 = url.substring(url.lastIndexOf("/")).trim();
        	String name=path1.substring(1);       
            
                File musics = new File("idownloads");
                if (!musics.exists()) {
                    musics.mkdirs();
                }      
            path = musics.getAbsolutePath();
              
          
             
            path=path+"\\"+name;
             System.out.println("path"+path);
             
                String f_head = path.substring(0, path.lastIndexOf("."));
                String f_suffix = path.substring(path.lastIndexOf(".")); // 含"."
                File f1 = new File(path);               // 最终保存文件
                File f2 = new File(path + "_");         // 未完成任务之前的文件名
                File f3 = new File(path + "_config");   // 状态保存文件
                // 检查并确保不存在相同名称的文件名，saveChange标识（存在相同的文件名)
                System.out.print(" f_head "+f_head +"1 :"+f1.exists()+" 2:"+f2.exists()+ " 3:"+f3.exists());
//               if(f1.exists() || f2.exists() || f3.exists()) {
                
                if(f1.exists() ) { //有一个漏洞，不能多个文件下载，不然会有问题
            	                 	
                	/*int option = JOptionPane.showConfirmDialog(null, "你存在下载文件，是否进行切换序列号", "提示",JOptionPane.YES_NO_OPTION);
    				if (option == JOptionPane.YES_OPTION){
    					System.out.println("this is OK Action");
    				}else{
    					
    				}*/
    				return true;
                	
                }else{
                	return false;
                }          
           
    }
    
}
